// src/components/Sensor.tsx
import { Card } from 'antd';
import faker from 'faker-zh-cn'; // 使用中文 locale

import React, { useEffect, useState } from 'react';
type SensorType = 'temperature' | 'humidity' | 'light' | 'airQuality';

interface SensorProps {
  type: SensorType;
  interval: number;
  sendData: (data: SensorData) => void;
}

interface SensorData {
  type: SensorType;
  data: string;
  timestamp: string;
  address: string;
  ip: string;
  id: string;
  status: string;
}

const Sensor: React.FC<SensorProps> = ({ type, interval, sendData }) => {
  const [sensorData, setSensorData] = useState<SensorData>({
    type,
    data: '',
    timestamp: '',
    address:
      faker.address.streetAddress() + ', ' + faker.address.city() + ', China',
    ip: faker.internet.ip(),
    id: faker.datatype.uuid(),
    status: 'active',
  });

  const generateRandomData = (type: SensorType): string => {
    switch (type) {
      case 'temperature':
        return (Math.random() * 30 + 15).toFixed(2); // Random temperature between 15°C and 45°C
      case 'humidity':
        return (Math.random() * 100).toFixed(2); // Random humidity between 0% and 100%
      case 'light':
        return (Math.random() * 1000).toFixed(0); // Random light between 0 lux and 1000 lux
      case 'airQuality':
        return (Math.random() * 300).toFixed(0); // Random air quality index between 0 and 300
      default:
        return '0';
    }
  };

  useEffect(() => {
    const timer = setInterval(() => {
      const newData = {
        type,
        data: generateRandomData(type),
        timestamp: new Date().toLocaleString(),
        address:
          faker.address.streetAddress() +
          ', ' +
          faker.address.city() +
          ', 中国',
        ip: faker.internet.ip(),
        id: sensorData.id,
        status: 'active',
      };
      setSensorData(newData);
      sendData(newData);
    }, interval);

    return () => clearInterval(timer);
  }, [type, interval, sendData, sensorData.id]);

  return (
    <Card
      title={`${type.charAt(0).toUpperCase() + type.slice(1)} Sensor`}
      style={{ marginBottom: 16 }}
    >
      <p>Current Data: {sensorData.data}</p>
      <p>Time: {sensorData.timestamp}</p>
      <p>Address: {sensorData.address}</p>
      <p>IP: {sensorData.ip}</p>
      <p>Status: {sensorData.status}</p>
    </Card>
  );
};

export default Sensor;
